package com.hy.utils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.*;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

public class FileUtils {
    //上传文件
    public static String FileUpload(Part part, String path, HttpServletRequest request) {
        // 判断图片是否上传
        String fileName = "";
        String fileName1 = "";
        if (part.getSize() > 0) {
            //获取文件名称
            fileName = part.getSubmittedFileName();
            //生成唯一的文件名
            String name = UUID.randomUUID().toString();
            //截取文件后缀
            fileName1 = path+"/"+name+fileName.substring(fileName.lastIndexOf("."));
            fileName = "/"+name+fileName.substring(fileName.lastIndexOf("."));
            fileName = String.format("/%s%s",name,fileName.substring(fileName.lastIndexOf(".")));
            // 得到当前项目真实路径
            String image = request.getServletContext().getRealPath("/imgs/upload");
            // 存储文件
            try {
                part.write(image + fileName);
            } catch (IOException e) {
                e.printStackTrace();
                fileName = "";
            }
        }
        return fileName1;
    }

    public static String saveImage(String imageData, ServletContext servletContext) {
        try {
            // 去掉Base64数据前缀
            String base64Image = imageData.substring(imageData.indexOf(',') + 1);

            byte[] decodedBytes = Base64.getDecoder().decode(base64Image);

            // 获取图像的文件扩展名
            String fileExtension = getFileExtensionFromImageData(imageData);

            // 构建带有扩展名的文件名
            String fileName = UUID.randomUUID().toString() + "." + fileExtension;

            // 获取Web应用程序内 'imgs/upload' 目录的真实路径
            String uploadPath = servletContext.getRealPath("/imgs/upload");

            // 确保目标目录存在
            Files.createDirectories(Paths.get(uploadPath));

            //存放临时路径
            Path targetPath = Paths.get(uploadPath, fileName);

            // 使用 try-with-resources 语句确保文件流关闭
            try (FileOutputStream fos = new FileOutputStream(targetPath.toFile())) {
                fos.write(decodedBytes);
            }

            return "/zhihu1/imgs/upload/" + fileName;
        } catch (Exception e) {
            e.printStackTrace(); // 在实际应用中可能需要记录日志
            return "default/image.png";
        }
    }

    private static String getFileExtensionFromImageData(String imageData) {
        String[] parts = imageData.split(";base64,");
        if (parts.length > 0) {
            String mimeType = parts[0].replace("data:image/", "");
            switch (mimeType) {
                case "jpeg":
                    return "jpg";
                case "png":
                    return "png";
                default:
                    return "png"; // 默认后缀名
            }
        }
        return "png"; // 默认后缀名
    }
}
